<template>
    <div class="xiaoqu">
        <h1>小区模块组件</h1>
        <div class="input">
            <div>
                <span>小区名称：</span>
                <el-input class="shuru" v-model="inputxiaoqu" placeholder="请输入内容">{{inputxiaoqu}}</el-input>
            </div>
            <div class="block">
                <span class="demonstration">创建时间：</span>
                <el-date-picker
                        v-model="value1"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    {{value1}}
                </el-date-picker>
                <el-button style="margin-left: 10px" @click="search" type="primary">搜索</el-button>
            </div>

        </div>

        <el-button type="primary" style="margin-bottom:20px" @click="dialogFormVisible = true">新增小区</el-button>

        <el-dialog title="小区新增" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="门店名称" :label-width="formLabelWidth">
                    <el-input v-model="form.mendianname" autocomplete="off">{{form.mendianname}}</el-input>
                </el-form-item>

                <el-form-item label="所属地区" :label-width="formLabelWidth">
                    <el-cascader
                            :options="addressAll"
                            clearable
                            v-model="address"
                            :props="{value:'label'}"

                    ></el-cascader>

                    <h1>{{address.join('')}}</h1>
                </el-form-item>

                <el-form-item :label-width="formLabelWidth">
                    <el-input v-model="form.date1" placeholder="请填写详细地址" autocomplete="off">{{form.date1}}</el-input>
                </el-form-item>

                <el-form-item label="门店坐标" :label-width="formLabelWidth">
                    <el-button @click="huoquposition" :plain="true">获取位置</el-button>
                    <span>&nbsp;&nbsp;{{form.weizhi}}</span>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="isok">确 定</el-button>
            </div>
        </el-dialog>

        <template>
            <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    :header-cell-style="{'background-color':'rgb(24, 144, 255)','color':'white','text-align':' center'}"
                    :cell-style="{'text-align':'center'}"
            >
                <el-table-column
                        fixed
                        prop="communityId"
                        label="ID"
                >
                </el-table-column>
                <el-table-column
                        prop="communityName"
                        label="名称"
                >
                </el-table-column>
                <el-table-column
                        prop="communityAddress"
                        label="位置"
                >
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="用户数量"
                >
                </el-table-column>
                <el-table-column
                        prop="communityShopCount"
                        label="关联门店"
                >
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="创建时间"
                >
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                >
                    <template slot-scope="scope">
                        <el-button @click="handleClick(scope.row)" type="text" size="small">查看关联门店</el-button>
                        <el-button type="text" size="small" @click="bianjixiaoquIndex( scope.row)">编辑小区
                        </el-button>
                        <el-button type="text" size="small" @click="removexiaoquIndex( scope.row.communityId)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>

        <el-dialog title="编辑小区" :visible.sync="bianjixiaoqu">
            <el-form :model="form2">
                <el-form-item label="门店名称" :label-width="formLabelWidth">
                    <el-input v-model="form2.mendianname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所属地区" :label-width="formLabelWidth">
                    <el-cascader
                            :options="addressAll"
                            clearable
                            v-model="form2.address"
                            :props="{value:'label'}"

                    ></el-cascader>
                    <!--  <h1>{{address}}</h1>-->
                    <h1>{{form2.address.join('')}}</h1>
                </el-form-item>

                <el-form-item :label-width="formLabelWidth">
                    <el-input v-model="form2.date1" placeholder="请填写详细地址" autocomplete="off">{{form2.date1}}</el-input>
                </el-form-item>

                <el-form-item label="门店坐标" :label-width="formLabelWidth">
                    <el-button @click="xiugaiisok" :plain="true">获取位置</el-button>
                    <span>&nbsp;&nbsp;{{form2.pos}}</span>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="bianjixiaoqu = false">取 消</el-button>
                <el-button type="primary" @click=" bianjixiaoqubaocun">确 定</el-button>
            </div>
        </el-dialog>

        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>


    </div>
</template>

<script>

    export default {
        name: "XiaoQuComponent",
        data() {
            return {
                inputxiaoqu: '',
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }],

                },
                tableData: [],
                bianjixiaoqu: false,
                dialogFormVisible: false,
                form: {
                    mendianname: '',
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: '',
                    weizhi: '',
                },
                form2: {
                    mendianname: '',
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: '',
                    pos: "",
                    address: []
                },
                // isok:"确定",
                id: "",

                formLabelWidth: '120px',

                addressAll: [],   //省市区
                address: [], //你选择的地址

                value1: '',
                value2: '',

                xiugai: [],

                weizhi1: "",
                weizhi2: "",
                weizhi3: "",
                weizhi4: "",


                total:0,//总条数
                currentPage: 1, //当前页数
                pageSize: 10, //每页获取条数（页面大小）

            };
        },
        methods: {
            //编辑小区
            bianjixiaoquIndex(index) {
                // console.log(this.form)
                this.form2.mendianname = index.communityName;
                // console.log(this.xiaoquguanli);
                this.form2.address = (index.communityProvince + "," + index.communityCity + "," + index.communityDistrict).split(",")
                // console.log(this.form2.address);
                this.form2.date1 = index.communityAddress;
                // // console.log(this.addmess);
                this.form2.pos = index.communityLatitude + "," + index.communityLongitude;
                // console.log(this.form2.pos);
                this.bianjixiaoqu = true;
                this.id = index.communityId;
            },
            bianjixiaoqubaocun() {
                this.axios.post("/community/communityUpdate",
                    {
                        addOrUpdateFlag: 2,
                        communityAddress: this.form2.date1,
                        communityAreaCode: 0,
                        communityCity: this.form2.address[1],
                        communityCoordinates: " ",
                        communityDistrict: this.form2.address[2],
                        communityId: this.id,
                        communityLatitude: this.weizhi3,
                        communityLongitude: this.weizhi4,
                        communityName: this.form2.mendianname,
                        communityProvince: this.form2.address[0],
                        communityShopCount: 0,
                        communityStatus: 1,
                        communityUserCount: 0,
                        createTime: this.getDateString(new Date()),
                        distance: null
                    }
                ).then(() => {
                    this.bianjixiaoqu = false;
                    this.shujuAll();
                }).catch(err => {
                    "错误1"
                })
            },
            xiugaiisok() {
                if (this.form2.date1 == '') {
                    this.$message.error('请填写详细地址');
                } else {
                    let url = "https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=" + this.form2.address;
                    this.axios(url).then(res => {
                        this.form2.pos = res.data.geocodes[0].location;
                        let a = this.form2.pos.split(",");
                        this.weizhi3 = a[0];
                        this.weizhi4 = a[1];
                    }).catch(err => {
                    });
                }
            },
            //获取省市
            getAllProvinceAndCityList() {
                // 获取全国所有省份和城市的列表
                var that = this;
                this.$http
                    .get("https://restapi.amap.com/v3/config/district", {
                        // 高德地图的API
                        params: {
                            key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
                            keywords: "中国",
                            subdistrict: 3,
                            extensions: "base",
                        },
                    })
                    .then((response) => {
                        console.log(response.data)
                        for (let i = 0; i < response.data.districts[0].districts.length; i++) {
                            let provinceMap = new Map();
                            provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
                            provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
                            provinceMap.children = [];
                            that.addressAll.push(provinceMap);  //添加省份
                            for (let j = 0; j < response.data.districts[0].districts[i].districts.length; j++) {
                                let cityMap = new Map()
                                cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                                cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                                cityMap.children = [];
                                provinceMap.children.push(cityMap); //添加市
                                for (let k = 0; k < response.data.districts[0].districts[i].districts[j].districts.length; k++) {
                                    let areaMap = new Map()
                                    areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                                    areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                                    cityMap.children.push(areaMap);   //添加区县
                                }
                            }
                        }
                    });
            },

            handleClick(row) {
                console.log(row);
            },
            handleSizeChange(size) {
                this.pageSize = size;
                // 可以在这里重新获取数据
                this.shujuAll();
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                // 可以在这里重新获取数据
                this.shujuAll()
            },


            getDateString(date) {
                // let str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                // return str;
                if (!date) {
                    return ""
                }
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            search() {
                if (!this.value1) {
                    this.value1 = "";
                }
                this.axios.get("/community/communityList", {
                    params: {
                        name: this.inputxiaoqu,
                        startTime: this.getDateString(this.value1[0]),
                        endTime: this.getDateString(this.value1[1]),
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        communityName: this.inputxiaoqu,
                    }
                }).then(res => {
                  console.log("我是搜索",res)
                    this.tableData = res.data.data.list;
                    this.total=res.data.data.total
                    // let time= getDateString(this.input)
                    console.log(this.value1, this.input)
                }).catch(err => {
                    "错误"
                })

            },
            isok() {
                this.axios.post("/community/addCommunity",
                    {
                        addOrUpdateFlag: 1,
                        communityAddress: this.form.date1,
                        communityAreaCode: "",
                        communityCity: this.address[1],
                        communityCoordinates: " ",
                        communityDistrict: this.address[2],
                        communityId: "",
                        communityLatitude: this.weizhi1,
                        communityLongitude: this.weizhi2,
                        communityName: this.form.mendianname,
                        communityProvince: this.address[0],
                    }
                ).then(res => {
                    this.shujuAll();
                }).catch(err => {
                })
                this.dialogFormVisible = false;
            },
            shujuAll() {
                this.axios.get("/community/communityList",{
                params:{
                    name: this.inputxiaoqu,
                    startTime: this.getDateString(this.value1[0]),
                    endTime: this.getDateString(this.value1[1]),
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    communityName: this.inputxiaoqu,
                }
            }
    ).then(res => {
        this.tableData = res.data.data.list;
        this.total=res.data.data.total

        // console.log(this.tableData)
        console.log("woshores", res);
    }).catch(err => {
    });
    },
    removexiaoquIndex(index)
    {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.axios.post(`/community/communityDelete`, {
                communityId: index,
            })
                .then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.shujuAll();
                })
                .catch(error => {
                    this.$message.error('删除失败，请重试'); // 处理删除失败的情况
                    console.error('删除失败', error);
                });
        }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });
        });

    }
    ,
    huoquposition()
    {
        if (this.form.date1 == '') {
            this.$message.error('请填写详细地址');
        } else {
            let url = "https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=" + this.address;
            this.axios(url).then(res => {
                this.form.weizhi = res.data.geocodes[0].location;
                let a = this.form.weizhi.split(",");
                this.weizhi1 = a[0];
                this.weizhi2 = a[1];
                console.log(res.data);
            }).catch(err => {
            });
        }
    }
    ,
    },
    created()
    {
        this.shujuAll();
        this.getAllProvinceAndCityList();
    }
    ,

    }
</script>

<style scoped>
    .xiaoqu {
        /*height: 100%;*/
        /*height: 800px;*/
        /*background-color: greenyellow;*/
        padding: 20px;
    }

    .input {
        display: flex;
        flex-wrap: wrap;
        justify-content: left;
    }

    .input > div {
        margin: 20px 0;
    }

    span {
        font-size: 16px;
    }

    .shuru {
        width: 200px;
        height: 36px;
        padding: 0 15px;

    }

    /*.xinzeng {*/
    /*    margin: 20px 0;*/
    /*    width: 100px;*/
    /*    background-color: #409eff;*/
    /*    color: white;*/
    /*}*/

    /*.xinzeng:hover {*/
    /*    background-color: rgb(102, 177, 255);*/
    /*}*/


</style>